package com.macrounion.atv.config;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.LocaleResolver;

import com.google.common.base.Strings;
import com.macrounion.base.service.dto.BaseRespDto;
import com.macrounion.base.service.exception.BusinessException;
@ControllerAdvice(basePackages={"com.macrounion.atv.controller.api"})
public class ExceptionAdviceController {
	
	 @Autowired
     private MessageSource messageSource;
	 @Autowired
	 private LocaleResolver localeResolver;
	 @Autowired
	 public HttpServletRequest request;
	
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler
	@ResponseBody
	public BaseRespDto<String> handlerException(Exception e){
		
		String msg = e.getMessage();
		if(Strings.isNullOrEmpty(msg)){
			msg = e.toString();
		}
		int defaultCode = 401;
		if (e instanceof BusinessException) {
			defaultCode = ((BusinessException)e).getCode();
			try {msg = messageSource.getMessage(msg, null, localeResolver.resolveLocale(request));}catch(Exception ex) {//字符未翻译	
				}
		}
		else{
			e.printStackTrace();
		}
		return new BaseRespDto<>(defaultCode, msg);
	}
}
